package com.dev.security.manager.controllers;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.security.login.beans.LoginUser;
import com.dev.security.login.service.LoginManager;
import com.dev.security.manager.beans.Account;
import com.dev.security.manager.beans.App;
import com.dev.security.manager.service.IAccountService;
import com.dev.security.manager.service.IAppService;
import com.dev.security.manager.service.IPermissionService;
import com.dev.security.util.Response;

/**
 * 管理页面
 * @author 潜行的青衣
 * @see
 */
@Controller
@RequestMapping("/manager/")
public class ManagerController {

	@Resource
	private IAppService appService;
	
	@Resource
	private IPermissionService permissionService;
	
	@Resource
	private LoginManager loginManager;
	
	@Autowired
	private IAccountService accountService;
	
	/**
	 * 管理首页
	 * @author 潜行的青衣
	 * @version
	 * @return
	 */
	@RequestMapping("index")
	public String index() {
		return "index";
	}
	
	@RequestMapping("apps")
	public @ResponseBody List<App> apps(
			HttpServletRequest request, HttpServletResponse response) {
		LoginUser user = loginManager.getLoginUser(request, response);
		if(user != null) {
			//root用户
			if(StringUtils.equalsIgnoreCase("root", user.getUserAccount())) {
				return this.appService.findAllApps();
			}
			return this.appService.findApps(user.getRoleIds());
		}
		return new ArrayList<App>();
	}
	
	@RequestMapping("permissions")
	public @ResponseBody Map<String, Boolean> permissions(
			HttpServletRequest request, HttpServletResponse response, String app_id) {
		//禁止缓存
		response.setHeader("pragma", "no-cache") ;
		response.setHeader("cache-control", "no-cache") ;
		response.setHeader("Expires", "0") ;
		Map<String, Boolean> result = new LinkedHashMap<String, Boolean>();
		if(StringUtils.isNotEmpty(app_id)) {
			LoginUser user = loginManager.getLoginUser(request, response);
			if(user != null) {
				if(StringUtils.equalsIgnoreCase("root", user.getUserAccount())) {
					result = this.permissionService.findPermissionMap(app_id);
				} else {
					result = this.permissionService.findPermissionMap(user.getRoleIds(), app_id);
				}
			}
		}
		return result;
	}
	
	@RequestMapping("account")
	public @ResponseBody Response account(
			HttpServletRequest request, HttpServletResponse response) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		return new Response(user != null, user);
	}
	
	@RequestMapping("password")
	public @ResponseBody Response password(
			HttpServletRequest request, HttpServletResponse response,
			String oldPassword, String password) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		//校验原有密码
		if(loginManager.getPasswordEncoder().matches(oldPassword, user.getUserPassword())) {
			Account account = (Account) user;
			account.setPassword(loginManager.getPasswordEncoder().encode(password));
			accountService.update(account);
			return new Response(true);
		}
		return new Response(false);
	}
	
	@RequestMapping("backgrounds")
	public @ResponseBody List<Map<String, String>> backgrounds(
			HttpServletRequest request, HttpServletResponse response) {
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		LoginUser user = this.loginManager.getLoginUser(request, response);
		String path = "/resources/images/backgrounds/";
		File dir = new File(
				request.getSession().getServletContext()
					.getRealPath(path));
		this.addToBackgrounds(path, dir, "system", result);
		
		path = new StringBuilder().append(path)
				.append(user.getUserId()).append("/").toString();
		dir = new File(
				request.getSession().getServletContext()
					.getRealPath(path));
		this.addToBackgrounds(path, dir, "mine", result);
		return result;
	}
	
	private void addToBackgrounds(String path, File dir, String group, List<Map<String, String>> backgrounds) {
		Map<String, String> background = null;
		if(dir.isDirectory()) {
			File[] files = dir.listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					return pathname.isFile();
				}
				
			});
			for(File file:files) {
				background = new LinkedHashMap<String, String>();
				background.put("text", new StringBuilder()
					.append(path).append(file.getName()).toString());
				background.put("group", group);
				backgrounds.add(background);
			}
		}
	}
	
}
